import { createRouter, createWebHistory } from 'vue-router'
import Register from '@/views/Register'
import Login from '@/views/Login'
import Home from '@/views/Home'
import Shop from '@/views/Shop/Shop'
import OrderConfirmation from '@/views/orderConfirmation/OrderConfirmation'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/shop/:id',
    name: 'Shop',
    component: Shop
  },
  {
    path: '/order-confirmation/:id',
    name: 'OrderConfirmation',
    component: OrderConfirmation
  },

  {
    path: '/login',
    name: 'Login',
    component: Login,
    beforeEnter (to, from, next) {
      const isLogin = localStorage.getItem('userIdentity')?.startsWith('Bearer')
      if (isLogin && to.name === 'Login') {
        console.log('home')
        next({ name: 'Home' })
        return
      }
      console.log('login')
      next()
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const isLogin = localStorage.getItem('userIdentity')?.startsWith('Bearer')
  console.log(isLogin)
  if (isLogin || to.name === 'Login' || to.name === 'Register') {
    next()
    return
  }
  next({ name: 'Login' })
})
export default router
